import React, { Component } from 'react';
import { message } from 'antd';
import services from '../../services/api';
import Modal from '../../components/Modal/index';
import { getCodeByKey } from '../../utils/utils';
import FilterToolColumnTitle from '../../components/FilterTool/FilterToolColumnTitle';

export default class CommonListsIndex extends Component {
  constructor(props) {
    super(props);
    this.state = {
      records: [],
      applications: [], //业务需要
      events: [], //业务需要
      products: [], // 业务需要，产品筛选
      defaultColumns: [], //默认要展示的列
      tabKey: '',
    };
    this.loading = false;
    this.api = '';
    this.addComponent = '';
    this.editComponent = '';
    this.listsComponent = '';
    this.model_width = undefined;
    if (props && props.location && props.location.search) {
      this.app_id = getCodeByKey(props.location.search, 'app_id');
      this.product_id = getCodeByKey(props.location.search, 'product_id');
      this.event_id = getCodeByKey(props.location.search, 'event_id');
      this.field_id = getCodeByKey(props.location.search, 'field_id');
      this.feature_id = getCodeByKey(props.location.search, 'feature_id');
      this.is_system = getCodeByKey(props.location.search, 'is_system');
    }

    this.initQueryPanigation = {
      // 初始化分页参数
      current: 1,
      size: 10,
    };
    this.queryPanigation = this.initQueryPanigation; //分页参数
    this.queryTableParams = {}; //表格列上的筛选参数
    this.queryParams = {}; //其他的筛选参数
    this.initApplications = []; // 初始化的全部渠道
    this.initProducts = []; // 初始化的全部产品
  }
  getFilterTitle = (title, options, searchKey, callback, [key, value], disabled = false) => {
    const data = options.filter((item) => item[key] !== -1);
    const finnalyData = data.length > 0 ? [{ [key]: -1, [value]: '全部' }, ...data] : [];
    return (
      <FilterToolColumnTitle
        title={title}
        options={[
          ...finnalyData.map((item) => {
            return {
              value: item[key],
              name: item[value],
            };
          }),
        ]}
        refreshTableFilter={callback ? callback : this.refreshTableFilter}
        selectedIds={
          this.queryTableParams && this.queryTableParams[searchKey] ? [this.queryTableParams[searchKey]] : []
        }
        searchKey={searchKey}
        disabled={disabled}
      />
    );
  };

  // 更新this.queryParams，重置分页参数为第一页，并搜索（主要用于filterTool的回调）,type表示是否更新数据还是只更新参数
  refreshFilter = (params, type = true) => {
    this.queryParams = params;
    if (!type) return;
    //  清除掉大数据分页的这些参数
    // this.queryPanigation.previous_id && delete this.queryPanigation.previous_id;
    // this.queryPanigation.next_id && delete this.queryPanigation.next_id;
    // this.queryPanigation.previous_page && delete this.queryPanigation.previous_page;
    // this.queryPanigation.total_count && delete this.queryPanigation.total_count;
    this.updatePanagaition(this.initQueryPanigation);
    this.freshQueryList();
  };

  // 仅更新筛选分页的参数
  updatePanagaition = (params) => {
    this.queryPanigation = {
      ...this.queryPanigation,
      ...params,
    };
  };
  // 分页回调
  onChangePagination = (pageNumber, type = 'current') => {
    console.log('pageNumber', pageNumber);
    if (this.state.previousId && this.state.nextId && this.state.previousPage && this.state.totalCount) {
      this.updatePanagaition &&
        this.updatePanagaition({
          [type]: pageNumber,
          previous_id: this.state.previousId,
          next_id: this.state.nextId,
          previous_page: this.state.previousPage,
          total_count: this.state.totalCount,
        });
    } else {
      this.updatePanagaition &&
        this.updatePanagaition({
          [type]: pageNumber,
        });
    }

    this.freshQueryList();
  };

  // 更新this.queryTableParams，并重置分页参数为第一页，再搜索
  refreshTableFilter = (params, { clearEvent = false, clearHitStrategyId = false } = {}) => {
    this.queryTableParams = { ...this.queryTableParams, ...params };
    const newQueryTableParams = {};
    // 循环key,非事件和渠道，遇到-1的值代表是全部，则不传
    for (let key in this.queryTableParams) {
      if (this.queryTableParams[key].toString() !== '-1') {
        newQueryTableParams[key] = this.queryTableParams[key];
      } else {
        if (key === 'app_id' || key === 'event_id') {
          newQueryTableParams[key] = this.queryTableParams[key];
        }
      }
    }
    this.queryTableParams = newQueryTableParams;
    // 如果需要清除event_id
    if (clearEvent) {
      delete this.queryTableParams.event_id;
    }
    // 如果需要清除clearHitStrategyId
    if (clearHitStrategyId) {
      delete this.queryTableParams.strategy_id;
    }

    //  清除掉大数据分页的这些参数
    this.queryPanigation.previous_id && delete this.queryPanigation.previous_id;
    this.queryPanigation.next_id && delete this.queryPanigation.next_id;
    this.queryPanigation.previous_page && delete this.queryPanigation.previous_page;
    this.queryPanigation.total_count && delete this.queryPanigation.total_count;

    this.updatePanagaition(this.initQueryPanigation);
    this.freshQueryList();
  };

  tabChange = (key) => {
    this.setState({ tabKey: key }, () => {
      this.resetList();
      this.freshQueryList();
    });
  };

  getTabParams = () => {
    if (!this.tabs || this.tabs.length === 0) return {};
    let key = this.tabs[0].keyName;
    let tabParams = { [key]: this.state.tabKey ? this.state.tabKey : this.tabs[0].key };
    return tabParams;
  };

  // 筛选列表，含参数
  freshQueryList = () => {
    this.queryList({
      ...this.queryParams,
      ...this.queryTableParams,
      ...this.queryPanigation,
      ...this.getTabParams(),
    });
  };

  // 重置筛选项
  resetList = () => {
    this.queryPanigation = Object.assign({}, this.initQueryPanigation);
    this.queryTableParams = {};
    this.queryParams = {};
    if (this.state.events && this.state.events.length > 0) {
      this.setState({
        applications: this.initApplications,
        products: this.initProducts,
        events: [],
      });
    }
  };

  // 重置筛选项并搜索
  resetListAndSearch = () => {
    this.resetList();
    this.freshQueryList();
  };

  // 列表
  queryList(params = {}) {
    this.setState({
      loading: true,
    });
    services[this.api].list(params).then((res) => {
      if (res.code === '0') {
        const { records, total } = res.data;
        const currentPage = params.current;
        const page = Math.ceil(total / this.queryPanigation.size);
        if (records && total && records.length === 0 && currentPage > page) {
          this.onChangePagination(page, 'current');
        } else {
          this.setState({
            ...res.data,
          });
        }
      } else {
        message.error(res.msg);
      }
      this.setState({
        loading: false,
      });
    });
  }

  clearList() {
    this.setState({
      records: [],
      total: 0,
      size: 10,
      current: 1,
    });
  }

  // 取消选中
  clearSelected = () => {};

  // 业务挂钩的，渠道列表请求
  // getAppCodeList = ({ product_id = -1, event_id = -1 } = {}) => {
  //   services.application.getAppCodeList({ product_id, event_id }).then((res) => {
  //     if (res.code === 0) {
  //       this.setState({
  //         applications: res.data,
  //       });
  //       if (this.initApplications.length === 0) this.initApplications = res.data;
  //     }
  //   });
  // };

  // 业务挂钩的，产品列表请求
  // getProductCodeList = ({ app_id = -1, event_id = -1 } = {}) => {
  //   services.product.getProductCodeList({ app_id, event_id }).then((res) => {
  //     if (res.code === 0) {
  //       this.setState({
  //         products: res.data,
  //       });
  //       if (this.initProducts.length === 0) this.initProducts = res.data;
  //     }
  //   });
  // };

  // 业务挂钩的，事件列表请求
  // getEventCodeList = ({ app_id = -1, product_id = -1 } = {}) => {
  //   services.event.getEventCodeList({ app_id, product_id }).then((res) => {
  //     if (res.code === 0) {
  //       this.setState({
  //         events: res.data,
  //       });
  //     }
  //   });
  // };
  // // 业务挂钩的，渠道改变，更新事件list,并且重新搜索列表
  // refreshTableFilterWithApp = (params) => {
  //   this.getEventCodeList(params.app_id); // 重新拉取事件列表
  //   this.refreshTableFilter(params, { clearEvent: true }); // 更新table筛选参数并拉取数据,清除event_id
  // };

  // 业务挂钩的，渠道改变，更新事件list,并且重新搜索列表
  // refreshTableFilterWithAppV2(key, params) {
  //   let newTableParams = { ...this.queryTableParams, ...params };
  //   let keyList = {
  //     app_id: newTableParams.app_id,
  //     product_id: newTableParams.product_id,
  //     event_id: newTableParams.event_id,
  //   };
  //   if (key !== 'app_id') this.getAppCodeList(keyList); // 重新拉取事件列表
  //   if (key !== 'product_id') this.getProductCodeList(keyList); // 重新拉取产品列表
  //   if (key !== 'event_id') this.getEventCodeList(keyList);
  //   this.refreshTableFilter(params); // 更新table筛选参数并拉取数据,清除event_id
  // }

  // 重置列
  setColumn = (values) => {
    this.setState({
      defaultColumns: values,
    });
  };

  // 表列定义
  getColumns = () => {
    return [];
  };

  add = ({ title }) => {
    const AddComponent = this.addComponent;
    if (typeof AddComponent === 'string') {
      this.props.history.push(AddComponent);
    } else if (AddComponent instanceof Object) {
      Modal.open({
        title: title || '新增',
        width: this.model_width ? this.model_width : '1000px',
        content: (
          <AddComponent
            {...this.props}
            closeModal={this.closeModal}
            actionType='add'
            dataType={this.state.dataType}
            applications={this.state.applications}
          />
        ),
        isOkBtn: false,
        maskClosable: false,
        isCancelBtn: false,
      });
    } else {
      console.log('something error');
    }
  };

  replaceUrlForId = (url, id) => {
    return url.replace(`/id/`, `/${id}/`);
  };

  edit = (record, { title }) => {
    const EditComponent = this.editComponent;
    if (typeof EditComponent === 'string') {
      this.props.history.push(this.replaceUrlForId(EditComponent, this.getOpenParam(record)));
    } else if (EditComponent instanceof Object) {
      Modal.open({
        title: title || '编辑',
        width: this.model_width ? this.model_width : '1000px',
        content: (
          <EditComponent
            value={record}
            record={record}
            closeModal={this.closeModal}
            dataType={this.state.dataType}
            actionType='update'
            treeData={this.state.listsData}
            {...this.props}
            applications={this.state.applications}
          />
        ),
        maskClosable: false,
        isOkBtn: false,
        isCancelBtn: false,
      });
    } else {
      console.log('something error');
    }
  };

  showDetail = (record, title, width) => {
    const EditComponent = this.editComponent;

    if (typeof EditComponent === 'string') {
      this.props.history.push(this.replaceUrlForId(EditComponent, this.getOpenParam(record)));
    } else if (EditComponent instanceof Object) {
      const index = Modal.open({
        title: title || '详情',
        width: width ? width : this.model_width ? this.model_width : '1000px',
        content: (
          <EditComponent
            record={record}
            value={record}
            closeModal={this.closeModal}
            dataType={this.state.dataType}
            actionType='detail'
            treeData={this.state.listsData}
            {...this.props}
            applications={this.state.applications}
          />
        ),
        isOkBtn: true,
        isCancelBtn: true,
        ok: () => {
          Modal.close(index);
        },
      });
    } else {
      console.log('something error');
    }
  };

  copy = (record) => {
    const EditComponent = this.editComponent;
    if (typeof EditComponent === 'string') {
      this.props.history.push(this.replaceUrlForId(EditComponent, this.getOpenParam(record)));
    } else if (EditComponent instanceof Object) {
      Modal.open({
        title: '复制',
        width: this.model_width ? this.model_width : '1000px',
        content: (
          <EditComponent
            record={record}
            value={record}
            closeModal={this.closeModal}
            dataType={this.state.dataType}
            actionType='copy'
            treeData={this.state.listsData}
            {...this.props}
          />
        ),
        isOkBtn: false,
        isCancelBtn: false,
      });
    } else {
      console.log('something error');
    }
  };

  closeModal = (onlyClose) => {
    if (onlyClose === true) {
      this.onlyCloseModal();
    } else {
      this.onlyCloseModal();
      this.freshQueryList();
    }
  };

  onlyCloseModal = () => {
    Modal.close();
  };

  // 打开新窗口、页面的id
  getOpenParam = (record) => {
    return record.id;
  };
}
